package com.haibei.view;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.common.uitl.Constant;
import com.common.uitl.DrawTool;
import com.common.uitl.LogUtil;
import com.common.uitl.StringUtils;
import com.haibei.R;

public class BackAsnycImageView extends ImageView {

	private Drawable mDefaultDrable;
	private String url;
	private static String cache_dir = "sdcard/imgcache";
	private Bitmap bitmapContent = null;
	private DowloadTask mDownloadTask;
	private boolean isStop = false;
	private boolean isRound = false;

	public BackAsnycImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
		try {
			cache_dir = context.getCacheDir().getAbsolutePath();
		} catch (Exception e) {
			e.printStackTrace();
		}
		TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.AsnycImage);
		mDefaultDrable = array.getDrawable(R.styleable.AsnycImage_defaultDrable);
		array.recycle();
		File fcacheFile = new File(cache_dir);
		if (!fcacheFile.exists()) {
			fcacheFile.mkdirs();
		}
	}

	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		if (url.equals(this.url)) {
			return;
		}
		this.url = url;
		if (null != mDownloadTask && !mDownloadTask.isCancelled()) {
			mDownloadTask.cancel(true);
		}
		mDownloadTask = new DowloadTask();
		mDownloadTask.execute(url);
	}

	public void setUrl(String url, boolean isRound) {
		this.isRound = isRound;
		if (url.equals(this.url)) {
			return;
		}
		this.url = url;
		if (null != mDownloadTask && !mDownloadTask.isCancelled()) {
			mDownloadTask.cancel(true);
		}
		mDownloadTask = new DowloadTask();
		mDownloadTask.execute(url);
	}

	public InputStream getNetWorkDrableInputStream(String address) {
		InputStream ins = null;
		try {
			URL url = new URL(address);
			URLConnection conection = url.openConnection();
			ins = conection.getInputStream();
		} catch (Exception e) {
			LogUtil.e(Constant.TAG, "图片下载失败：" + address);
		}

		return ins;
	}

	class DowloadTask extends AsyncTask<String, Void, Bitmap> {
		@Override
		protected Bitmap doInBackground(String... arg0) {
			String url = arg0[0];
			InputStream inputs = null;
			Bitmap map = null;
			try {
				String urlEncodeFileName = URLEncoder.encode(url, "utf-8");
				String avialePath = cache_dir + File.separator + urlEncodeFileName;
				File cf = new File(avialePath);
				if (cf.exists()) {
					try {
						map = BitmapFactory.decodeFile(avialePath);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				if (null != map) {
					return map;
				}
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			// =====================

			if (!StringUtils.isEmpty(url)) {
				try {
					inputs = getNetWorkDrableInputStream(url);
					if (null != inputs) {
						map = BitmapFactory.decodeStream(inputs);
						String fpath = cache_dir + File.separator + URLEncoder.encode(url, "utf-8");
						if (null != map) {
							map.compress(CompressFormat.JPEG, 75, new FileOutputStream(fpath));
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			if (isRound) {
				try {
					map = DrawTool.toRoundCorner(map, 10);
				} catch (Exception e) {
					// e.printStackTrace();
					LogUtil.e(Constant.TAG, "图片下载失败：" + url);
				}
			}
			return map;
		}

		@Override
		protected void onPostExecute(Bitmap result) {
			updateView(result);
		}
	}

	public void updateView(Bitmap result) {
		if (isStop == false) {
			if (null != result) {
				if (null != bitmapContent && !bitmapContent.isRecycled()) {
					bitmapContent.recycle();
				}
				if (null != result && !result.isRecycled()) {
					setBitmapContent(result);
					Drawable drable = DrawTool.scaleDrable2FitScreen(getContext(), new BitmapDrawable(result));
					setBackgroundDrawable(drable);
					invalidate();
				}
				return;
			} else {
				setBackgroundDrawable(mDefaultDrable);
			}
		}

	}

	public void recycle() {
		this.isStop = true;
		// recycle调用很耗时，如果在主线程回收，当页面退出的时候会导致前一个页面崩溃,但是这里还需要考虑内存回收
		// if (null != this.bitmapContent && !this.bitmapContent.isRecycled()) {
		// this.bitmapContent.recycle();
		// LogUtil.i(Constant.TAG, "回收：" + this.url);
		// }
		this.bitmapContent = null;
		new Thread(new Runnable() {
			@Override
			public void run() {
				if (null != bitmapContent && !bitmapContent.isRecycled()) {
					bitmapContent.recycle();
					LogUtil.i(Constant.TAG, "回收：" + url);
				}
			}
		}).start();
		// setBackgroundDrawable(null);
	}

	@Override
	protected void finalize() throws Throwable {
		super.finalize();
		recycle();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// if (null == bitmapContent || !bitmapContent.isRecycled()) {
		// setImageBitmap(bitmapContent);
		// } else {
		// setImageDrawable(mDefaultDrable);
		// }
		super.onDraw(canvas);
	}

	public Drawable getmDefaultDrable() {
		return mDefaultDrable;
	}

	public void setmDefaultDrable(Drawable mDefaultDrable) {
		this.mDefaultDrable = mDefaultDrable;
	}

	public Bitmap getBitmapContent() {
		return bitmapContent;
	}

	public void setBitmapContent(Bitmap bitmapContent) {
		this.bitmapContent = bitmapContent;
	}

}
